package com.xingchi.tornado.storage.core;

import com.xingchi.tornado.core.utils.RandomUtils;
import com.xingchi.tornado.storage.core.exception.FileNotFoundException;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 文件存储服务模块
 *
 * @author xingchi
 * @date 2024/4/8 21:36
 */
public abstract class AbstractFileStorageService implements FileStorageService {


    protected static final byte[] EMPTY_BYTES = new byte[0];

    private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("/yyyy/MMdd/HHmm/");

    protected String getPath(String fileName) {
        return "/storage" + DATE_TIME_FORMATTER.format(LocalDateTime.now()) + RandomUtils.getRandomStringAndNumber(8) + "." + FilenameUtils.getExtension(fileName);
    }

    protected String getPath(String start, String fileName) {
        return FilenameUtils.separatorsToUnix(FilenameUtils.normalize((StringUtils.equalsAny(start, "/", "\\") ? "" : start) + fileName));
    }

    @Override
    public String uploadFile(String path) {
        if (StringUtils.isBlank(path)) {
            throw new FileNotFoundException(String.format("文件不存在[%s]", path));
        }
        try {
            return uploadFile(Files.newInputStream(Paths.get(path)), FilenameUtils.getName(path));
        } catch (IOException e) {
            throw new FileNotFoundException(String.format("文件不存在[%s]", path));
        }
    }

    /**
     * 文件上传
     *
     * @param path 文件存储路径
     * @return 文件在文件存储服务器上的路径唯一标识，在云存储中返回文件的对象名
     */
    @Override
    public String uploadFile(Path path) {
        if (path == null || !Files.exists(path)) {
            throw new FileNotFoundException(String.format("文件不存在[%s]", path));
        }

        try {
            return uploadFile(Files.newInputStream(path), FilenameUtils.getName(path.toFile().getName()));
        } catch (IOException e) {
            throw new FileNotFoundException(String.format("文件不存在[%s]", path));
        }
    }

    @Override
    public String uploadFile(byte[] bytes, String fileName) {
        return uploadFile(new ByteArrayInputStream(bytes), fileName);
    }

}
